import pygame
from .info import Info
from .clinet import Clinet
from . import constants as C


class LoadScreen:
    def __init__(self, clinet):
        self.finished = False
        self.score = 0
        self.state = ["snake", "over"]
        self.next = self.state[0]
        self.info = Info("load_screen", 0)
        self.timer = 0
        self.clinet = clinet

    def draw(self, surface):
        surface.fill((255, 255, 255))
        self.info.draw(surface)

        # if self.timer == 0:
        #     self.timer = pygame.time.get_ticks()
        # elif pygame.time.get_ticks() - self.timer > 2000:
        #     self.finished = True
        #     self.timer = 0

    def update(self, surface, keys):
        self.draw(surface)
        if self.clinet.finished:  #匹配成功
            self.next = self.state[0]
            self.finished = True
        else:
            if self.timer == 0:
                self.clinet.get_connection()
                self.timer = -1
            self.matching()
            pass

    def matching(self):
        data = self.clinet.connection.recv(256).decode()  #重复接收来自服务器的匹配信息
        #服务器拒绝服务，人数已满，退出程序
        if (data.startswith("msg(拒绝)")):
            print("msg ", data)
            self.clinet.connection.close()
            quit()

        #服务器同意加入游戏，全局变量my_id记录本客户端编号
        elif (data.startswith("msg(同意)")):
            self.clinet.my_id = int(data.split("为：")[1])
            print(f"my_id: {self.clinet.my_id}")

        #服务器匹配完成
        elif (data.startswith("msg(匹配完成)")):
            # print("msg ", data)
            msg = (f"msg: 客户端 {self.clinet.my_id} 收到指令，准备就绪")  #回传准备就绪
            self.clinet.connection.sendall(str.encode(msg))
            self.clinet.finished = True
            # break  #退出匹配阶段
        # pass